<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" type="image/ico"
	href="http://www.datatables.net/media/images/favicon.ico" />

<title>DataTables example</title>
<style type="text/css" title="currentStyle">
@import "style/dt_page.css";
@import "style/dt_table.css";
@import "style/bullbuddy.css";
</style>
<script type="text/javascript" language="javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/param.js"></script>
<script type="text/javascript" charset="utf-8">
	var cofId = "0001";
	var startTime="2014-01-05 20:00:00";
	var timeDiv = "";
   	$(document).ready(pageInit);
	
	function pageInit(){
  		//初始化服务器时间
  		initTime();
 		//初始化数据表
  		var oTable = $('#table_id').dataTable({
			"bProcessing" : true,
			"bServerSide" : true,
			"bAutoWidth": false,
			"sAjaxSource" : "service/test",
			"sAjaxDataProp":"cfSignList",
			"bServerSide":false,
			"bSortCellsTop": true,
			"fnServerParams": function ( aoData ) {
		    	aoData.push( { "name": "cofId", "value": cofId } );
		    },
			"oLanguage": {
			      "sUrl": "locale/data-tables.zh_CN"
			    },
			"aoColumns": [
					            { "mData": "staffId" },
					            { "mData": "staffName" },
					            { "mData": "departmentId" },
					            { "mData": "signingTime" },
					            { "mData": "lateTime" },
					            { "mData": "signingFlag" }
					         ],
			"aoColumnDefs": [
			                 { "sClass": "staffId", "aTargets": [ 0 ] },
			                 { "sClass": "staffName", "aTargets": [ 1 ] },
			                 { "sClass": "departmentId", "aTargets": [ 2 ] },
			                 { "sClass": "signingTime", "aTargets": [ 3 ] },
			                 { "sClass": "lateTime", "aTargets": [ 4 ] },
			                 { "sClass": "signingFlag", "aTargets": [ 5 ] },
			                 {
			                     "aTargets": [5],
			                     "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
			                    	if ( sData == "0")
			                    		oTable.fnUpdate('未签到',iRow,iCol);
			           		        else if( sData == "1" )
			           		        	oTable.fnUpdate('已签到',iRow,iCol);
			           		        else if( sData == "2" )
			           		        	oTable.fnUpdate('已签到（受委托）',iRow,iCol);
			                     }
			                 }
			                ],
	 		"fnInitComplete": function(oSettings, json) {
				postDataTableInit(oTable);
			}
		});		
	}
  	function getRowByStaffId(staffId){
  		var ret = undefined;
  		//检查页面上的内容：是否存在该条记录。
  		$("#sign-list td.staffId").each(function(){
  			if($(this).text()==staffId){
  				ret = $(this).parent();
  				return false;
  			}
   		});
    	return ret;
  	}
  	
  	function registerSignButton(oTable){
  		 //登记按钮
		 $("#signBtn").click(function(){
			  var staffId=$("#signInput").val();
				//记录存在与签到表中 
				var row = getRowByStaffId(staffId);
			  	if(row){
			  		/*
					更新页面显示
					*/
					{
						var iRow = $("tbody tr").index($(row));
						var cell = $(row).find("td.signingFlag");
						alert(iRow)
						if($(cell).text()=="未签到"){
							oTable.fnUpdate("已签到",iRow,5);
							var localTime = new Date().getTime();
							oTable.fnUpdate(new Date(localTime - timeDiv).toLocaleString(),iRow, 3);
							var lateTime = parseInt(((localTime - timeDiv) - Date.parse(startTime))/1000/60);
							oTable.fnUpdate(""+lateTime,iRow, 4);
						}else{
							alert("该与会者已经签到！");
							return;
						}
					}
				  /*
				   更新后台数据
				  */
				  {
					  $.ajax(
						{
							url : "service/test",
							type : "post",
							data : {"action":"OP_UPDATE","cofId":cofId,"staffId":staffId,"startTime":startTime},
							dataType : "json"
					  	}).done(//查到该职工，则更新到页面上
							function(cfSign) {
								if (cfSign ) {
									//根据职工号查询的只有一条记录
									var c = cfSign;
								} else if (cfSign.error) { //若返回的对象包含error字段，查询失败
									$("#error-msg").html(cfSign.error);
								}
						}).fail(
							function(cfSign){//查不到该员工，则提示不存在该职工
							
							}
						);//--end fail
				  }
			}else{
					$.ajax({
						 url : "service/cofSign",
						 type : "post",
						 data : {"cofId":td_cofId,"staffId":td_staffId,"staffName":td_staffName,"fg":fg},
						 dataType : "json"
					 }).done(//查到该职工，则更新到页面上
						 function(cfSign) {
					  } ).fail(function(cfSign){//请求失败
					 });//--end fail
			     }//--end else
		 });//--end signBtn Click
  	}
  	function postDataTableInit(oTable){
  		//初始化数据表的查询框
 		initFilterBox(oTable);
 		registerSignButton(oTable);
  	}
  	
  	function initTime(){
  		$.ajax(
  			{
  			url : "service/time",
			type : "post",
			dataType : "json"
  			}
  		).done(function(obj){
  			if(obj.time){
  				serverTime = obj.time;
  				var local = new Date().getTime();
  				timeDiv = local - serverTime;
   			}
   		});
   	}
 
  	function appendRecord(){
  		$('#table_id').dataTable().fnAddData(
  		                                     {"staffId":"asd",
  		                                      "staffName":"sss",
  		                                      "departmentId":"dfdf",
  		                                      "signingTime":"gdfgfg",
  		                                      "lateTime":"nvbn",
  		                                      "signingFlag":"df"}
  											);
  	}
  	
  	function initFilterBox(oTable){
  		//设置输入框搜索功能
  		$("thead input").keyup( function () {
  			var iColumn = $(this).attr("cloumn-index");
   			oTable.fnFilter( this.value, oTable.oApi._fnVisibleToColumnIndex( 
  				oTable.fnSettings(), iColumn ) );
  		} );
  		
  		//输入框的一些事件 
  		$("thead input").each( function (i) {
  			this.initVal = this.value;
  		} );
  		$("thead input").focus( function () {
  			if ( this.className == "search_init" )
  			{
  				this.className = "search_box";
  				this.value = "";
  			}
  		} );
  		$("thead input").blur( function (i) {
  			if ( this.value == "" )
  			{
  				this.className = "search_init";
  				this.value = this.initVal;
  			}
  		} );
  		
  		//设置选择框的筛选功能
  		$("thead select").each( function () {
  			var iColumn = $(this).attr("cloumn-index");
  			var colLabel = $(this).attr("cloumn-name");
  	        var aData = fnGetColumnData(oTable, colLabel,true);
  	      	var options,i, iLen=aData.length;
  	      	options += "<option value=''>--全部--</option>";
    	    for ( i=0 ; i<iLen ; i++ )
    	    {
    	    	options += '<option value="'+aData[i]+'">'+aData[i]+'</option>';
    	    }
    	    $(this).append(options);
  	        $(this).change( function () {
  	            oTable.fnFilter($(this).val(),  iColumn);
  	        } );
  	    } );
  	}
  	
  	function fnGetColumnData(oTable, colLabel, bUnique){
  		var data = oTable.fnGetData();
  		var iLen = data.length, i;
  		var arr = [];
  		for(i=0;i<iLen;i++){
  			var aData = data[i];
		    var sValue = eval("data["+ i +"]."+colLabel);
		         
			if ( sValue && sValue.length == 0) continue;
		    else if (bUnique == true && jQuery.inArray(sValue, arr) > -1) continue;
		    else arr.push(sValue);
  		}
  		return arr;
  	}
</script>
</head>
<body id="dt_example">
<div id="container">
<div>
	<span style="font-size: 16px; padding: 4px;">扫描输入信息</span>
	<input id="signInput" type="text" style="border: none; border-bottom: solid 2px; width: 300px;font-size: 20px; padding: 4px; font-weight: bold; background-image: url('');" />
	<button id="signBtn" style="font-size: 16px;">登记</button>
</div>
<div id="dynamic">
		<center>	
			<table id="table_id" class="display" >
				<thead>
					<tr>
						<th>职工号</th>
						<th>姓名</th>
						<th>部门号</th>
						<th>签到时间</th>
						<th>迟到时间</th>
						<th>与会状态</th>
					</tr>
					<tr>
						<td><input type="text" value="搜索职工号" class="search_init" cloumn-index="0"/></td>
						<td><input type="text" value="搜索姓名"  class="search_init" cloumn-index="1"/></td>
						<td>
							<select cloumn-index="2" cloumn-name="departmentId">
							</select>
						</td>
						<td><input type="text" value="搜索签到时间"  class="search_init" cloumn-index="3"/></td>
						<td><input type="text" value="搜索迟到时间"  class="search_init" cloumn-index="4"/></td>
						<td>
							<select cloumn-index="5" cloumn-name="signingFlag">
							</select>
						</td>
					</tr>
				</thead>
				<tbody id="sign-list">
					<tr>
						<td>正在加载数据...</td>
					</tr>
				</tbody>
			</table>
		</center>
	</div>
</div>
<button onclick="appendRecord();">add</button>
</body>
</html>